package com.authine.cloudpivot.web.api.secondopen.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.web.api.config.HxConfig;
import com.authine.cloudpivot.web.api.dubbo.DubboConfigService;
import com.authine.cloudpivot.web.api.secondopen.dao.Ie6s6KmjcxxMapper;
import com.authine.cloudpivot.web.api.secondopen.dao.Ie6s6QadgysMaintainMapper;
import com.authine.cloudpivot.web.api.secondopen.domain.Ie6s6Kjdwxx;
import com.authine.cloudpivot.web.api.secondopen.domain.Ie6s6Kmjcxx;
import com.authine.cloudpivot.web.api.secondopen.domain.Ie6s6QadgysMaintain;
import com.authine.cloudpivot.web.api.secondopen.domain.Sendresult;
import com.authine.cloudpivot.web.api.secondopen.modules.*;
import com.authine.cloudpivot.web.api.secondopen.modules.AdAddrAndNameVO;
import com.authine.cloudpivot.web.api.secondopen.modules.CreditorTypeVO;
import com.authine.cloudpivot.web.api.secondopen.modules.CustomerVO;
import com.authine.cloudpivot.web.api.secondopen.modules.ProductVO;
import com.authine.cloudpivot.web.api.secondopen.modules.ProviderVO;
import com.authine.cloudpivot.web.api.secondopen.modules.VoucherVO;
import com.authine.cloudpivot.web.api.secondopen.service.QadInterfaceService;
import com.authine.cloudpivot.web.api.secondopen.utils.HttpRestUtil;
import com.authine.cloudpivot.web.api.utils.DateUtil;
import com.authine.cloudpivot.web.api.utils.StringUtils;
import io.jsonwebtoken.lang.Collections;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@Service
public class QadInterfaceServiceImpl implements QadInterfaceService {

    private static final Logger log = LoggerFactory.getLogger(QadInterfaceServiceImpl.class);

    @Autowired
    private HxConfig hxConfig;

    @Autowired
    private Ie6s6QadgysMaintainMapper ie6s6QadgysMaintainMapper;

    @Autowired
    private DubboConfigService dubboConfigService;

    @Autowired
    private Ie6s6KmjcxxMapper ie6s6KmjcxxMapper;

    @Autowired
    private ProductionManagementServiceImpl productionManagementService;

    @Override
    @Transactional
    public void syncSubjectDataInService() {
        String url = hxConfig.getQadurl();
        String token = hxConfig.getToken();
        String xdomain = hxConfig.getXdomain();
        String result = HttpRestUtil.httpGetUrlWithoutEncrypt(url, "", xdomain, "qad_asc_mstr", "token");
        log.info("------------------------" + JSON.toJSONString(result));
        JSONObject jsonObject = JSONObject.parseObject(result);
        int successNum = 0;
        int errorNum = 0;
        int delNum = 0;
        if (result != null) {
            JSONArray jsonArray = jsonObject.getJSONArray("data");
            log.info("**列表接口返回:{}", jsonArray);
            if (jsonArray != null && jsonArray.size() > 0) {
                int size = jsonArray.size();
                //查询所有账户信息
                List<Ie6s6Kmjcxx> ie6s6Kmjcxxs = ie6s6KmjcxxMapper.selectKmjcxx();
                Map<String, String> kmjcxxMap = new HashMap<>();
                //转化为map集合
                if (!Collections.isEmpty(ie6s6Kmjcxxs)) {
                    for (Ie6s6Kmjcxx ie6s6Kmjcxx : ie6s6Kmjcxxs) {
                        if (StringUtils.isNotBlank(ie6s6Kmjcxx.getOneaccountcode()) && StringUtils.isNotBlank(ie6s6Kmjcxx.getTwoaccountcode())) {
                            String code = ie6s6Kmjcxx.getOneaccountcode() + "-" + ie6s6Kmjcxx.getTwoaccountcode();
                            String name = ie6s6Kmjcxx.getOneaccountname() + "-" + ie6s6Kmjcxx.getTwoaccountname();
                            kmjcxxMap.put(code, name);
                        }
                    }
                }
                //定义用于比对本地和QAD删除的数据
                Map<String, String> kmjcxxTwoMap = new HashMap<>();
                for (int i = 0; i < size; i++) {
                    JSONObject syncObject = (JSONObject) jsonArray.get(i);
                    try {
                        if (syncObject != null) {
                            String oneCode = syncObject.getString("qad_asc_acc");
                            //*****需要hr提供
                            String twoCode = syncObject.getString("qad_asc_sub");
                            String oneName = syncObject.getString("qad_asc_acc");
                            //*****需要hr提供
                            String twoName = syncObject.getString("qad_asc_sub");
                            String code = oneCode + "-" + twoCode;
                            String name = oneName + "-" + twoName;
                            kmjcxxTwoMap.put(code, name);
                            if (StringUtils.isNotBlank(oneCode) && StringUtils.isNotBlank(twoCode)) {
                                if (Collections.isEmpty(kmjcxxMap)) {
                                    //如果本地没有供应商数据，则全部为新增
                                    Ie6s6Kmjcxx Ie6s6Kmjcxx = this.convertKmjcxxInfo(oneCode, twoCode, oneName, twoName);
                                    if (ie6s6KmjcxxMapper.insertKmjcxx(Ie6s6Kmjcxx) > 0) {
                                        successNum++;
                                    }
                                } else {
                                    if (!kmjcxxMap.containsKey(code)) {
                                        //如果map不存在该供应商code，则为新增
                                        Ie6s6Kmjcxx Ie6s6Kmjcxx = this.convertKmjcxxInfo(oneCode, twoCode, oneName, twoName);
                                        if (ie6s6KmjcxxMapper.insertKmjcxx(Ie6s6Kmjcxx) > 0) {
                                            successNum++;
                                        }
                                    } else {
                                        //如果map存在该供应商code，并且供应商名称不一致，则为修改
                                        if (!name.equals(kmjcxxMap.get(code))) {
                                            Ie6s6Kmjcxx ie6s6Kmjcxx = new Ie6s6Kmjcxx();
                                            ie6s6Kmjcxx.setOneaccountcode(oneCode);
                                            ie6s6Kmjcxx.setTwoaccountcode(twoCode);
                                            ie6s6Kmjcxx.setOneaccountname(oneName);
                                            ie6s6Kmjcxx.setOneaccountname(twoName);
                                            ie6s6Kmjcxx.setYyxt("QAD");
                                            ie6s6Kmjcxx.setModifiedtime(new Date());
                                            if (ie6s6KmjcxxMapper.updateKmjcxx(ie6s6Kmjcxx) > 0) {
                                                successNum++;
                                            }
                                        }
                                    }

                                }

                            }
                        }
                    } catch (Exception e) {
                        errorNum++;
                        log.info("异常供应商信息为{}", JSON.toJSONString(syncObject));
                        log.error("同步供应商信息异常，异常信息：" + e.getMessage());
                        continue;
                    }

                }

                if (!Collections.isEmpty(ie6s6Kmjcxxs)) {
                    for (Ie6s6Kmjcxx ie6s6Kmjcxx : ie6s6Kmjcxxs) {
                        if (StringUtils.isNotBlank(ie6s6Kmjcxx.getOneaccountcode()) && StringUtils.isNotBlank(ie6s6Kmjcxx.getTwoaccountcode())) {
                            String code = ie6s6Kmjcxx.getOneaccountcode() + "-" + ie6s6Kmjcxx.getTwoaccountcode();
                            //如果QAD科目信息中存在数据库该数据，则跳过，不存在，则删除数据库多余数据
                            if (!kmjcxxTwoMap.containsKey(code)) {
                                if (ie6s6KmjcxxMapper.deleteKmjcxx(ie6s6Kmjcxx) > 0) {
                                    delNum++;
                                }
                            }
                        }
                    }
                }

            }
        }
        log.info("------------删除QAD与本地科目信息不一致成功条数为:{}条-----------", delNum);
        log.info("------------同步QAD科目信息成功条数为:{}条，同步科目失败条数为:{}条-----------", successNum, errorNum);

    }

    public Ie6s6Kmjcxx convertKmjcxxInfo(String oneCode, String twoCode, String oneName, String twoName) {
        Ie6s6Kmjcxx ie6s6Kmjcxx = new Ie6s6Kmjcxx();
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        ie6s6Kmjcxx.setId(uuid);
        ie6s6Kmjcxx.setOneaccountcode(oneCode);
        ie6s6Kmjcxx.setTwoaccountcode(twoCode);
        ie6s6Kmjcxx.setOneaccountname(oneName);
        ie6s6Kmjcxx.setTwoaccountname(twoName);
        ie6s6Kmjcxx.setName(oneName + "-" + twoName);
        ie6s6Kmjcxx.setCreater("");
        ie6s6Kmjcxx.setCreateddeptid("");
        ie6s6Kmjcxx.setOwner("");
        ie6s6Kmjcxx.setOwnerdeptid("");
        ie6s6Kmjcxx.setCreatedtime(new Date());
        ie6s6Kmjcxx.setModifier("");
        ie6s6Kmjcxx.setModifiedtime(new Date());
//        ie6s6QadgysMaintain.setSequenceno();
        ie6s6Kmjcxx.setSequencestatus("COMPLETED");
        ie6s6Kmjcxx.setOwnerdeptquerycode("1");
        ie6s6Kmjcxx.setYyxt("QAD");
        return ie6s6Kmjcxx;
    }

    @Override
    public void syncSupplierDataInService() {
        String url = hxConfig.getQadurl();
        String token = hxConfig.getToken();
        String xdomain = hxConfig.getXdomain();
        String result = HttpRestUtil.httpGetUrlWithoutEncrypt(url, "", xdomain, "qad_vd_mstr", token);
        log.info("------------------------" + JSON.toJSONString(result));
        JSONObject jsonObject = JSONObject.parseObject(result);
        int successNum = 0;
        int errorNum = 0;
        if (result != null) {
            JSONArray jsonArray = jsonObject.getJSONArray("data");
            log.info("**列表接口返回:{}", jsonArray);
            if (jsonArray != null && jsonArray.size() > 0) {
                int size = jsonArray.size();
                //查询所有供应商数据
                List<Ie6s6QadgysMaintain> ie6s6QadgysMaintains = ie6s6QadgysMaintainMapper.selectQadgysMaintain();
                Map<String, String> qadgysMap = new HashMap<>();
                //转化为map集合
                if (!Collections.isEmpty(ie6s6QadgysMaintains)) {
                    for (Ie6s6QadgysMaintain ie6s6QadgysMaintain : ie6s6QadgysMaintains) {
                        if (StringUtils.isNotBlank(ie6s6QadgysMaintain.getGyscode())) {
                            qadgysMap.put(ie6s6QadgysMaintain.getGyscode(), ie6s6QadgysMaintain.getGysname());
                        }
                    }
                }
                //将QAD的供应商信息保存在map中，用于本地对比，删除本地多余的供应商数据
                Map<String, String> qadgysTwoMap = new HashMap<>();
                for (int i = 0; i < size; i++) {
                    JSONObject syncObject = (JSONObject) jsonArray.get(i);
                    try {
                        if (syncObject != null) {
                            String gysCode = syncObject.getString("qad_vd_addr");
                            //*****需要hr提供
                            String gysName = syncObject.getString("qad_vd_addr");
                            qadgysTwoMap.put(gysCode, gysName);
                            if (StringUtils.isNotBlank(gysCode)) {
                                if (Collections.isEmpty(qadgysMap)) {
                                    //如果本地没有供应商数据，则全部为新增
                                    Ie6s6QadgysMaintain ie6s6QadgysMaintain = this.convertQadgysInfo(gysCode, gysName);
                                    if (ie6s6QadgysMaintainMapper.insertQadgysMaintain(ie6s6QadgysMaintain) > 0) {
                                        successNum++;
                                    }
                                } else {
                                    if (!qadgysMap.containsKey(gysCode)) {
                                        //如果map不存在该供应商code，则为新增
                                        Ie6s6QadgysMaintain ie6s6QadgysMaintain = this.convertQadgysInfo(gysCode, gysName);
                                        if (ie6s6QadgysMaintainMapper.insertQadgysMaintain(ie6s6QadgysMaintain) > 0) {
                                            successNum++;
                                        }
                                    } else {
                                        //如果map存在该供应商code，并且供应商名称不一致，则为修改
                                        if (!gysName.equals(qadgysMap.get(gysCode))) {
                                            Ie6s6QadgysMaintain ie6s6QadgysMaintain = new Ie6s6QadgysMaintain();
                                            ie6s6QadgysMaintain.setGyscode(gysCode);
                                            ie6s6QadgysMaintain.setGysname(gysName);
                                            ie6s6QadgysMaintain.setModifiedtime(new Date());
                                            if (ie6s6QadgysMaintainMapper.updateQadgysMaintainByGysCode(ie6s6QadgysMaintain) > 0) {
                                                successNum++;
                                            }
                                        }
                                    }

                                }

                            }
                        }
                    } catch (Exception e) {
                        errorNum++;
                        log.info("异常科目信息信息为{}", JSON.toJSONString(syncObject));
                        log.error("同步科目信息异常，异常信息：" + e.getMessage());
                        continue;
                    }
                }

                if (!Collections.isEmpty(ie6s6QadgysMaintains)) {
                    List<String> gysCodes = new ArrayList<>();
                    for (Ie6s6QadgysMaintain ie6s6QadgysMaintain : ie6s6QadgysMaintains) {
                        //如果QAD供应商信息中存在数据库该数据，则跳过，不存在，则删除数据库多余数据
                        if (!qadgysTwoMap.containsKey(ie6s6QadgysMaintain.getGyscode())) {
                            gysCodes.add(ie6s6QadgysMaintain.getGyscode());
                        }
                    }
                    log.info("本地存在但QAD不存在供应商Code为{}", JSON.toJSONString(gysCodes));
                    //批量删除QAD不存在的供应商数据
                    if (!Collections.isEmpty(gysCodes)) {
                        int num = ie6s6QadgysMaintainMapper.deleteQadgysMaintains(gysCodes.toArray(new String[gysCodes.size()]));
                        log.info("------------删除本地存在但QAD不存在的供应商信息条数为：{}-------------", num);
                    }
                }

            }
        }
        log.info("------------同步QAD科目信息成功条数为:{}条，同步科目失败条数为:{}条-----------", successNum, errorNum);

    }

    @Override
    public List<ProviderVO> providerInfoGet(Map<String, String> params) {
        String url = hxConfig.getQadurl();
        String xdomain = hxConfig.getXdomain();
        String xtoken = hxConfig.getToken();
        if (!CollectionUtil.isEmpty(params)) {
            //设置请求参数
            StringBuilder arg = null;
            arg = new StringBuilder();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                arg.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            url = url + "?" + arg.substring(0, arg.length() - 1);
        }
        String result = HttpRestUtil.httpGetUrlWithoutEncrypt(url, "04693esd-1564-4635-4s4e-6db6s6a8b95d", xdomain, "qad_vd_mstr", xtoken);
        log.info("------------------------" + JSON.toJSONString(result));
        JSONObject jsonObject = JSONObject.parseObject(result);
        List<ProviderVO> providerVOs = new ArrayList<>();
        if (!org.apache.commons.lang.StringUtils.isEmpty(result)) {
            JSONArray data = jsonObject.getJSONArray("data");
            log.info("**列表接口返回:{}", data);
            if (!CollectionUtils.isEmpty(data)) {
                int size = data.size();
                for (int i = 0; i < size; i++) {
                    ProviderVO providerVO = new ProviderVO();
                    JSONObject object = (JSONObject) data.get(i);
                    String qadVdAddr = object.getString("qad_vd_addr");
                    String qadVdBuyer = object.getString("qad_vd_buyer");
                    String qadVdShipvia = object.getString("qad_vd_shipvia");
                    providerVO.setQadVdAddr(qadVdAddr);
                    providerVO.setQadVdBuyer(qadVdBuyer);
                    providerVO.setQadVdShipvia(qadVdShipvia);
                    providerVOs.add(providerVO);
                }
            }
        }
        return providerVOs;
    }

    @Override
    public List<CustomerVO> customerInfoGet(Map<String, String> params) {
        String url = hxConfig.getQadurl();
        String xdomain = hxConfig.getXdomain();
        String xtoken = hxConfig.getToken();
        String corp = "04693esd-1564-4635-4s4e-6db6s6a8b95d";
        if (!CollectionUtil.isEmpty(params)) {
            //设置请求参数
            StringBuilder arg = null;
            arg = new StringBuilder();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                arg.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            url = url + "?" + arg.substring(0, arg.length() - 1);
        }
        String result = HttpRestUtil.httpGetUrlWithoutEncrypt(url, corp, xdomain, "qad_cm_mstr", xtoken);
        log.info("------------------------" + JSON.toJSONString(result));
        JSONObject jsonObject = JSONObject.parseObject(result);
        List<CustomerVO> customerVOs = new ArrayList<>();
        if (!org.apache.commons.lang.StringUtils.isEmpty(result)) {
            JSONArray data = jsonObject.getJSONArray("data");
            log.info("**列表接口返回:{}", data);
            if (!CollectionUtils.isEmpty(data)) {
                int size = data.size();
                for (int i = 0; i < size; i++) {
                    CustomerVO customerVO = new CustomerVO();
                    JSONObject object = (JSONObject) data.get(i);
                    String qadCmAddr = object.getString("qad_cm_addr");
                    String qadCmShip = object.getString("qad_cm_ship");
                    String qadCmCrTerms = object.getString("qad_cm_cr_terms");
                    customerVO.setQadCmAddr(qadCmAddr);
                    customerVO.setQadCmShip(qadCmShip);
                    customerVO.setQadCmCrTerms(qadCmCrTerms);
                    customerVOs.add(customerVO);
                }
            }
        }
        return customerVOs;
    }

    @Override
    public List<ProductVO> getProductNoByParamInterface(String oneSubjectCode, String twoSubjectCode, String cbzx) {
        String url = hxConfig.getQadurlheader();
        String xdomain = hxConfig.getXdomain();
        String xtoken = hxConfig.getToken();

//        if (!CollectionUtil.isEmpty(params)) {
//            //设置请求参数
//            StringBuilder arg = null ;
//            arg = new StringBuilder() ;
//            for(Map.Entry<String,String> entry : params.entrySet()){
//                arg.append(entry.getKey()).append("=").append(entry.getValue()).append("&") ;
//            }
//            url = url + "?" + arg.substring(0,arg.length()-1) ;
//        }
        url = url + "MdmProject/Get?icAcct=" + oneSubjectCode + "&icSub=" + twoSubjectCode + "&icCostCent=" + cbzx;
        String result = HttpRestUtil.httpGetUrlWithoutEncrypt(url, "", xdomain, "MdmProjectGet", xtoken);
        log.info("------------------------" + JSON.toJSONString(result));
        JSONObject jsonObject = JSONObject.parseObject(result);
        List<ProductVO> productNos = new ArrayList<>();
        if (StringUtils.isNotBlank(result)) {
            JSONArray data = jsonObject.getJSONArray("data");
            log.info("**列表接口返回:{}", data);
            if (!CollectionUtils.isEmpty(data)) {
                int size = data.size();
                for (int i = 0; i < size; i++) {
                    ProductVO productVO = new ProductVO();
                    JSONObject object = (JSONObject) data.get(i);
                    //项目号
                    String mdmProjectCode = object.getString("MdmProjectCode");
                    //项目名称
                    String mdmProjectDescription = object.getString("MdmProjectDescription");
                    productVO.setProductCode(mdmProjectCode);
                    productVO.setProductName(mdmProjectDescription);
                    productVO.setId(mdmProjectCode);
                    productNos.add(productVO);
                }
            }
        }
        return productNos;
    }

    @Override
    public BigDecimal getQadZshlByParam(String qadExrCurrZf, String qadExrCurrBzf) {
        String url = hxConfig.getQadurl();
        String xdomain = hxConfig.getXdomain();
        String xtoken = hxConfig.getToken();
        String date = DateUtil.getCurrentDate("yyyy-MM-dd");
//        String datea="2021-05-31";
//        String dateb="2021-06-29";
        url = url + "?qad_exr_curr1=" + qadExrCurrZf + "&qad_exr_curr2=" + qadExrCurrBzf + "&qad_exr_start_dateTo=" + date + "&qad_exr_end_dateFr=" + date;
        String result = HttpRestUtil.httpGetUrlWithoutEncrypt(url, "", xdomain, "qad_exr_rate", xtoken);
        log.info("------------------------" + JSON.toJSONString(result));
        JSONObject jsonObject = JSONObject.parseObject(result);
        BigDecimal rate = null;
        if (StringUtils.isNotBlank(result)) {
            JSONArray data = jsonObject.getJSONArray("data");
            log.info("**列表接口返回:{}", data);
            if (!CollectionUtils.isEmpty(data)) {
                JSONObject object = (JSONObject) data.get(0);
                if (object != null) {
                    rate = object.getBigDecimal("qad_exr_rate2");
                }
            }
        }
        return rate;
    }

    @Override
    public QadResultVO generateQadVoucher(VoucherVO voucherVO) {
        String url = hxConfig.getQadurlheader();
        String xdomain = hxConfig.getXdomain();
        String xtoken = hxConfig.getToken();
        url = url + "MdmBJournalentry/Post";
        String result = HttpRestUtil.httpPostUrlWithoutEncryptInLogin(url, "", xdomain, "MdmBJournalentryPost", xtoken, JSON.toJSONString(voucherVO));
        log.info("------------------------" + JSON.toJSONString(result));
        JSONObject jsonObject = JSONObject.parseObject(result);
        QadResultVO qadResultVO = new QadResultVO();
        if (StringUtils.isNotBlank(result)) {
            String code = jsonObject.getString("code");
            String msg = jsonObject.getString("msg");
            JSONArray data = jsonObject.getJSONArray("data");
            if (!CollectionUtils.isEmpty(data)) {
                JSONObject object = (JSONObject) data.get(0);
                qadResultVO.setPzh(object.getString("MdmOiPostingVoucher"));

            }
            qadResultVO.setCode(code);
            qadResultVO.setMsg(msg);
            qadResultVO.setData(data);
            log.info("**列表接口返回:{}", JSON.toJSONString(data));
        }
        return qadResultVO;

    }

    @Override
    public List<AdAddrAndNameVO> adAddrAndNamesGet(Map<String, String> params) {
        String url = hxConfig.getQadurl();
        String xdomain = hxConfig.getXdomain();
        String xtoken = hxConfig.getToken();
        if (!CollectionUtil.isEmpty(params)) {
            //设置请求参数
            StringBuilder arg = null;
            arg = new StringBuilder();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                arg.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            url = url + "?" + arg.substring(0, arg.length() - 1);
        }
        String result = HttpRestUtil.httpGetUrlWithoutEncrypt(url, "", xdomain, "qad_ad_mstr", xtoken);
        log.info("------------------------" + JSON.toJSONString(result));
        JSONObject jsonObject = JSONObject.parseObject(result);
        List<AdAddrAndNameVO> adAddrAndNameVOs = new ArrayList<>();
        if (!org.apache.commons.lang.StringUtils.isEmpty(result)) {
            JSONArray data = jsonObject.getJSONArray("data");
            log.info("**列表接口返回:{}", data);
            if (!CollectionUtils.isEmpty(data)) {
                int size = data.size();
                for (int i = 0; i < size; i++) {
                    AdAddrAndNameVO adAddrAndNameVO = new AdAddrAndNameVO();
                    JSONObject object = (JSONObject) data.get(i);
                    String qadAdAddr = object.getString("qad_ad_addr");
                    String qadAdName = object.getString("qad_ad_name");
                    adAddrAndNameVO.setQad_ad_addr(qadAdAddr);
                    adAddrAndNameVO.setQad_ad_name(qadAdName);
                    adAddrAndNameVO.setId(qadAdAddr);
                    adAddrAndNameVOs.add(adAddrAndNameVO);
                }
            }
        }
        return adAddrAndNameVOs;
    }

    @Override
    public List<CreditorTypeVO> getCreditorType(Map<String, String> params) {
        String url = hxConfig.getQadurl();
        String xdomain = hxConfig.getXdomain();
        String xtoken = hxConfig.getToken();
        if (!CollectionUtil.isEmpty(params)) {
            //设置请求参数
            StringBuilder arg = null;
            arg = new StringBuilder();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                arg.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            url = url + "?" + arg.substring(0, arg.length() - 1);
        }
        String result = HttpRestUtil.httpGetUrlWithoutEncrypt(url, "", xdomain, "qad_CreditorType", xtoken);
        log.info("------------------------" + JSON.toJSONString(result));
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(result)) {
            List<CreditorTypeVO> creditorTypeVOs = new ArrayList<>();
            JSONArray data = jsonObject.getJSONArray("data");
            log.info("**列表接口返回:{}", data);
            if (!CollectionUtils.isEmpty(data)) {
                int size = data.size();
                for (int i = 0; i < size; i++) {
                    CreditorTypeVO creditorTypeVO = new CreditorTypeVO();
                    JSONObject object = (JSONObject) data.get(i);
                    // 是否生效数据
                    boolean isActive = false;
                    isActive = object.getBoolean("qad_creditortype_creditortypeisactive");
                    if (isActive) {
                        creditorTypeVO.setId(object.getString("qad_creditortype_creditortype_id"));
                        creditorTypeVO.setCode(object.getString("qad_creditortype_creditortypecode"));
                        creditorTypeVO.setDescription(object.getString("qad_creditortype_creditortypedescription"));
                        creditorTypeVOs.add(creditorTypeVO);
                    }
                }
                return creditorTypeVOs;
            }
        }
        return null;
    }

    @Override
    public List<QadCInvoiceDeatail> getQadCInvoiceByParam(String startDate, String endDate, String gysCodeType) {
        String url = hxConfig.getQadurl();
        String xdomain = hxConfig.getXdomain();
        String xtoken = hxConfig.getToken();
        url = url + "?qad_cinvoice_creditorcode=" + gysCodeType + "&qad_cinvoice_cinvoiceduedateFr=" + startDate + "&qad_cinvoice_cinvoiceduedateTo=" + endDate;
        String result = HttpRestUtil.httpGetUrlWithoutEncrypt(url, "", xdomain, "qad_CInvoice", xtoken);
        log.info("------------------------" + JSON.toJSONString(result));
        JSONObject jsonObject = JSONObject.parseObject(result);
        List<QadCInvoiceDeatail> qadCInvoiceDeatails = new ArrayList<>();
        if (!org.apache.commons.lang.StringUtils.isEmpty(result)) {
            JSONArray data = jsonObject.getJSONArray("data");
            log.info("**列表接口返回:{}", data);
            if (!CollectionUtils.isEmpty(data)) {
                int size = data.size();
                for (int i = 0; i < size; i++) {
                    QadCInvoiceDeatail qadCInvoiceDeatail = new QadCInvoiceDeatail();
                    JSONObject object = (JSONObject) data.get(i);
                    String cinvoicedueDate = object.getString("qad_cinvoice_cinvoiceduedate");
                    String creditorCode = object.getString("qad_cinvoice_creditorcode");
                    String creditorName = object.getString("qad_cinvoice_creditorname");


                    String paymentconditionCode = object.getString("qad_cinvoice_paymentconditioncode");
                    String cinvoicereference = object.getString("qad_cinvoice_cinvoicereference");
                    String cinvoicepostingdate = object.getString("qad_cinvoice_cinvoicepostingdate");

                    String creditorIsActive = object.getString("qad_cinvoice_creditorIsActive");
                    //国内TC余额
                    Double cinvoicebalancelc = object.getDouble("qad_cinvoice_cinvoicebalancelc");
                    //国外TC余额
                    Double cinvoicebalancecc = object.getDouble("qad_cinvoice_cinvoicebalancecc");

                    qadCInvoiceDeatail.setCinvoicedueDate(cinvoicedueDate);
                    qadCInvoiceDeatail.setCreditorCode(creditorCode);
                    qadCInvoiceDeatail.setCreditorName(creditorName);
                    qadCInvoiceDeatail.setPaymentconditionCode(paymentconditionCode);
                    qadCInvoiceDeatail.setCinvoicereference(cinvoicereference);
                    qadCInvoiceDeatail.setCinvoicepostingdate(cinvoicepostingdate);
                    qadCInvoiceDeatail.setCreditorIsActive(creditorIsActive);
                    qadCInvoiceDeatail.setCinvoicebalancecc(cinvoicebalancecc);

                    qadCInvoiceDeatail.setCinvoicebalancelc(cinvoicebalancelc);

                    qadCInvoiceDeatails.add(qadCInvoiceDeatail);
                }
            }
        }

        if (!Collections.isEmpty(qadCInvoiceDeatails)) {
            //根据供应商编码累计支付前金额
            Map<String, Double> map = qadCInvoiceDeatails.stream().collect(Collectors.groupingBy(p -> p.getCreditorCode(), Collectors.summingDouble(QadCInvoiceDeatail::getCinvoicebalancelc)));
            System.out.println(JSON.toJSONString(map));
        }

        return qadCInvoiceDeatails;

    }

    @Override
    public List<QadCInvoiceDeatail> removalQadCInvoiceDeatails(List<QadCInvoiceDeatail> qadCInvoiceDeatails) {
        List<QadCInvoiceDeatail> qadDeatails=new ArrayList<>();
        qadCInvoiceDeatails.parallelStream().collect(Collectors.groupingBy(d -> d.getCreditorCode(), Collectors.toList()))
                .forEach((id, groupList) -> {
                    groupList.stream().reduce(
                            (a, b) -> new QadCInvoiceDeatail(a.getCreditorCode(),a.getCreditorName(),a.getCinvoicebalancelc(),b.getCinvoicebalancelc())
                    ).ifPresent(qadDeatails::add);
                });
        return qadDeatails;
    }

    @Override
    public List<SalesOrderVO> salesOrderGet(Map<String, String> params, Date time) {
        Date now = new Date();

        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");

        //测试环境参数
        /*String url = hxConfig.getQadurl();
        String xdomain = hxConfig.getXdomain();
        String xtoken = hxConfig.getToken();*/

        String url = "http://192.9.200.79:9092/api/CommonMaster/Get";
        String xdomain = hxConfig.getXdomain();
        String xtoken = "8c2e513b-3517-978f-96db-86edea680f98";


        if (!CollectionUtil.isEmpty(params)) {
            //设置请求参数
            StringBuilder arg = null;
            arg = new StringBuilder();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                arg.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            url = url + "?" + arg.substring(0, arg.length() - 1);
        }
        String result = HttpRestUtil.httpGetUrlWithoutEncrypt(url, "", xdomain, "qad_pi_mstr", xtoken);
        log.info("------------------------" + JSON.toJSONString(result));
        JSONObject jsonObject = JSONObject.parseObject(result);
        List<SalesOrderVO> salesOrderVOS = new ArrayList<>();
        if (!org.apache.commons.lang.StringUtils.isEmpty(result)) {
            JSONArray data = jsonObject.getJSONArray("data");
            log.info("**列表接口返回:{}", data);
            if (!CollectionUtils.isEmpty(data)) {
                int size = data.size();
                for (int i = 0; i < size; i++) {
                    SalesOrderVO salesOrderVO = new SalesOrderVO();
                    JSONObject object = (JSONObject) data.get(i);
                    String qadPiPartCode = object.getString("qad_pi_part_code");
                    String qadPiUm = object.getString("qad_pi_um");
                    String qadPiStart = object.getString("qad_pi_start");
                    String qadPiExpire = object.getString("qad_pi_expire"); //到期日期
                    String qadPiListPrice = object.getString("qad_pi_list_price");
                    String qadPiListId = object.getString("qad_pi_list_id");
                   /* //只要当前日期小于到期日期的数据
                    Date endTime = null;
                    try {
                        endTime = ft.parse(qadPiExpire);

                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    boolean boo = now.before(endTime);

                    if (boo) {
                        salesOrderVO.setQad_pi_part_code(qadPiPartCode);
                        salesOrderVO.setQad_pi_um(qadPiUm);
                        salesOrderVO.setQad_pi_expire(qadPiExpire);
                        salesOrderVO.setQad_pi_list_price(qadPiListPrice);
                        salesOrderVO.setQad_pi_start(qadPiStart);
                        //根据零件号查询零件名称
                        String qadPtName = productionManagementService.getPartInfo(qadPiPartCode).get(0).getName();
                        salesOrderVO.setQad_pt_name(qadPtName);
                        salesOrderVO.setId(qadPiListId);
                        salesOrderVOS.add(salesOrderVO);
                    } */
                   /* //只要当前日期小于到期日期的数据
                    Date endTime = null;
                    try {
                        endTime = ft.parse(qadPiExpire);

                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    boolean boo = now.before(endTime);

                    if (boo) {
                        salesOrderVO.setQad_pi_part_code(qadPiPartCode);
                        salesOrderVO.setQad_pi_um(qadPiUm);
                        salesOrderVO.setQad_pi_expire(qadPiExpire);
                        salesOrderVO.setQad_pi_list_price(qadPiListPrice);
                        salesOrderVO.setQad_pi_start(qadPiStart);
                        //根据零件号查询零件名称
                        String qadPtName = productionManagementService.getPartInfo(qadPiPartCode).get(0).getName();
                        salesOrderVO.setQad_pt_name(qadPtName);
                        salesOrderVO.setId(qadPiListId);
                        salesOrderVOS.add(salesOrderVO);
                    } */
                        salesOrderVO.setQad_pi_part_code(qadPiPartCode);
                        salesOrderVO.setQad_pi_um(qadPiUm);
                        salesOrderVO.setQad_pi_expire(qadPiExpire);
                        salesOrderVO.setQad_pi_list_price(qadPiListPrice);
                        salesOrderVO.setQad_pi_start(qadPiStart);
                        //根据零件号查询零件名称
                        String qadPtName = productionManagementService.getPartInfo(qadPiPartCode).get(0).getName();
                        salesOrderVO.setQad_pt_name(qadPtName);
                        salesOrderVO.setId(qadPiListId);
                        salesOrderVOS.add(salesOrderVO);
                }
            }
        }
        return salesOrderVOS;
    }

    @Override
    public List<LocVO> getAllLoc(String qadLoc) {
        String token = hxConfig.getToken();
        String url = hxConfig.getQadurl();
        String xdomain = hxConfig.getXdomain();
        String xcode = "qad_loc_mstr";
        url = url + "?qad_loc_loc=" + qadLoc;

        String result = HttpRestUtil.httpGetUrlWithoutEncrypt(url, "", xdomain, "qad_loc_mstr", token);
        log.info("------------------------" + JSON.toJSONString(result));
        JSONObject jsonObject = JSONObject.parseObject(result);
        ArrayList<LocVO> locVOS = new ArrayList<>();
        if (!org.apache.commons.lang.StringUtils.isEmpty(result)) {
            JSONArray data = jsonObject.getJSONArray("data");
            log.info("**列表接口返回:{}", data);
            if (!CollectionUtils.isEmpty(data)) {
                int size = data.size();
                for (int i = 0; i < size; i++) {
                    JSONObject object = (JSONObject) data.get(i);
                    LocVO locVO = new LocVO();
                    String qadLocLoc = object.getString("qad_loc_loc");
                    String qadLocSite = object.getString("qad_loc_site");
                    String qadLocDesc = object.getString("qad_loc_desc");
                    String qadLocDate = object.getString("qad_loc_date");
                    locVO.setId(i);
                    locVO.setQad_loc_loc(qadLocLoc);
                    locVO.setQad_loc_site(qadLocSite);
                    locVO.setQad_loc_desc(qadLocDesc);
                    locVO.setQad_loc_date(qadLocDate);

                    locVOS.add(locVO);
                }
            }
        }
        return locVOS;
    }

    @Override
    public QadResultVO qadInMdmBankEntryPost(MdmBankEntry mdmBankEntry) {
        String url = hxConfig.getQadurlheader();
        String xdomain = hxConfig.getXdomain();
        String xtoken = hxConfig.getToken();
        url = url + "MdmBankEntry/Post";
        String result = HttpRestUtil.httpPostUrlWithoutEncryptInLogin(url, "", xdomain, "MdmBankEntryPost", xtoken, JSON.toJSONString(mdmBankEntry));
        log.info("------------------------" + JSON.toJSONString(result));
        JSONObject jsonObject = JSONObject.parseObject(result);
        QadResultVO qadResultVO = new QadResultVO();
        if (StringUtils.isNotBlank(result)) {
            String code = jsonObject.getString("code");
            String msg = jsonObject.getString("msg");
            JSONArray data = jsonObject.getJSONArray("data");
            if (!CollectionUtils.isEmpty(data)) {
                JSONObject object = (JSONObject) data.get(0);
                qadResultVO.setPzh(object.getString("MdmOiPostingVoucher"));
            }
            qadResultVO.setCode(code);
            qadResultVO.setMsg(msg);
            qadResultVO.setData(data);
            log.info("**列表接口返回:{}", JSON.toJSONString(data));
        }
        return qadResultVO;
    }


    public Ie6s6QadgysMaintain convertQadgysInfo(String gysCode, String gysName) {
        Ie6s6QadgysMaintain ie6s6QadgysMaintain = new Ie6s6QadgysMaintain();
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        ie6s6QadgysMaintain.setId(uuid);
        ie6s6QadgysMaintain.setGyscode(gysCode);
        ie6s6QadgysMaintain.setGysname(gysName);
        ie6s6QadgysMaintain.setName(gysName + "[" + gysCode + "]");
        ie6s6QadgysMaintain.setCreater("");
        ie6s6QadgysMaintain.setCreateddeptid("");
        ie6s6QadgysMaintain.setOwner("");
        ie6s6QadgysMaintain.setOwnerdeptid("");
        ie6s6QadgysMaintain.setCreatedtime(new Date());
        ie6s6QadgysMaintain.setModifier("");
        ie6s6QadgysMaintain.setModifiedtime(new Date());
//        ie6s6QadgysMaintain.setSequenceno();
        ie6s6QadgysMaintain.setSequencestatus("COMPLETED");
        ie6s6QadgysMaintain.setOwnerdeptquerycode("1");
        return ie6s6QadgysMaintain;
    }


}